package com.northwind.aspect;

import com.northwind.annotation.AddLog;
import com.northwind.dao.LogMapper;
import com.northwind.entity.Admin;
import com.northwind.entity.Log;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author DeepHunter
 * 日志AOP
 */
@Aspect
@Configuration
public class LogAspect {
    @Resource
    HttpSession session;
    @Resource
    LogMapper logMapper;

    @Around("@annotation(com.northwind.annotation.AddLog)")//切注解   within类   excu..方法
    public Object addLog(ProceedingJoinPoint joinPoint){
        System.out.println("=====进入LogAspect环绕通知=====");
        //谁   时间    什么操作    是否成功
        Admin admin = (Admin) session.getAttribute("admin");
        //获取管理员名
        String username = admin.getUsername();
        //获取操作时间
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        Date nowTimeDate = null;
        String nowTime = simpleDateFormat.format(date);
        try {
            nowTimeDate = simpleDateFormat.parse(nowTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //获取方法名
        String methodname = joinPoint.getSignature().getName();
        System.out.println("方法名"+methodname);
        //进入环绕通知，执行目标方法
        //获取方法的签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取切到的方法
        //获取方法上的指定注解
        AddLog addLog = signature.getMethod().getAnnotation(AddLog.class);
        //获取注解上的属性值
        String value = addLog.value();
        String message = null;
        Object proceed = null;
        try {
            proceed = joinPoint.proceed();
            message = "SUCCESS";
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            message = "FAIL";
        }
        Log log = new Log(UUID.randomUUID().toString(),username,nowTimeDate,methodname+"("+value+")",message);
        System.out.println("进行的操作为:"+log);
        //数据入库
        logMapper.insert(log);
        return proceed;
    }
}
